"""
字符串相关操作方法共计47个，分为十大类：
一、大小写转换（1）——（6），共计6个
二、字符串居中、居左、居右的控制（7）——（10），共计4个
三、查找、统计子串（11）——（15），共计5个
四、格式化字符串（16）——（17），共计2个
五、判断字符串（18）——（31），共计14个
六、删除子串（32）——（36），共计5个
七、字符串连接（37），共计1个
八、字符串分割（38）——（42），共计5个
九、部分替换（43）——（45），共计3个
十、其它（46）——（47），共计2个
"""

print("""
一、大小写转换（1）——（6），共计6个
----------------------------------------
（1）str.capitalize()
  Return a capitalized version of the string.
  More specifically, make the first character have upper case and the rest lower
  case.
  返回首字母转换为大写的字符串
----------------------------------------""")
str1 = "return a capitalized version of the string."
print("str1={}".format(str1))
result = str1.capitalize()
print("str1.capitalize()执行结果为：",result)

print("""
----------------------------------------
（2）str.upper()
  Return a copy of the string converted to uppercase.
  转换字符串中所有小写字符为大写，并返回转换后的字符串
----------------------------------------""")
str2 = "Return a copy of the string converted to uppercase."
print("str2={}".format(str2))
result = str2.upper()
print("str2.upper()执行结果为：",result)

print("""
----------------------------------------
（3）str.lower()
  Return a copy of the string converted to lowercase.
  转换字符串中所有大写字符为小写，并返回转换后的字符串
----------------------------------------""")
str3 = "Return a copy of the string converted to lowercase."
print("str3={}".format(str3))
result = str3.lower()
print("str3.lower()执行结果为：",result)

print("""
----------------------------------------
（4）str.casefold()
  Return a version of the string suitable for caseless comparisons.
  返回将字符串中所有大写字符转换为小写后生成的字符串。
  此方法是Python3.3版本之后引入的，其效果和 lower() 方法非常相似，
  都可以转换字符串中所有大写字符为小写。两者的区别是：
  lower() 方法只对ASCII编码，也就是‘A-Z’有效，
  对于其他语言（非汉语或英文）中把大写转换为小写的情况只能用 casefold() 方法。
----------------------------------------""")

print("""
----------------------------------------
（5）str.swapcase()
  Convert uppercase characters to lowercase and lowercase characters to uppercase.
  将字符串中大写转换为小写，小写转换为大写
----------------------------------------""")
str5 = "Convert uppercase characters to lowercase and lowercase characters to uppercase."
print("str5={}".format(str5))
result = str5.swapcase()
print("str5.swapcase()执行结果为：",result)

print("""
----------------------------------------
（6）str.title()
  Return a version of the string where each word is titlecased.
  More specifically, words start with uppercased characters and all remaining
  cased characters have lower case.
  返回"标题化"的字符串,就是说所有单词都是以大写开始，其余字母均为小写(见 istitle())
----------------------------------------""")
str6 = "Return a version of the string where each word is titlecased."
print("str6={}".format(str6))
result = str6.title()
print("str6.title()执行结果为：",result)

print("""
二、字符串居中、居左、居右的控制（7）——（10），共计4个
----------------------------------------
（7）str.center(width, fillchar=' ')
  Return a centered string of length width.
  Padding is done using the specified fill character (default is a space).
  返回一个原字符串居中,并使用 fillchar(默认空格）填充至长度 width 的新字符串
----------------------------------------""")
str7 = "centered"
print("str7={}".format(str7))
result = str7.center(20, "*")
print("str7.center()执行结果为：",result)

print("""
----------------------------------------
（8）str.ljust(width, fillchar=' ')
  Return a left-justified string of length width.
  Padding is done using the specified fill character (default is a space).
  返回一个原字符串左对齐,并使用 fillchar(默认空格）填充至长度 width 的新字符串
----------------------------------------""")

print("""
----------------------------------------
（9）str.rjust(width, fillchar=' ')
  Return a right-justified string of length width.
  Padding is done using the specified fill character (default is a space).
  返回一个原字符串右对齐,并使用fillchar(默认空格）填充至长度 width 的新字符串
----------------------------------------""")

print("""
----------------------------------------
（10）str.zfill(width)
  Pad a numeric string with zeros on the left, to fill a field of the given width.
  The string is never truncated.
  返回长度为 width 的字符串，原字符串右对齐，前面填充0
----------------------------------------""")

print("""
三、查找、统计子串（11）——（15），共计5个
----------------------------------------
（11）str.count(sub[, start[, end]]) -> int
  Return the number of non-overlapping occurrences of substring sub in
  string S[start:end].  Optional arguments start and end are
  interpreted as in slice notation.
  返回 sub 在 string 里面出现的次数.
  如果 start 或者 end 指定,则返回指定范围内 sub 出现的次数
  start和end可以为负数，代表倒数的位置，最后一个字符为-1
----------------------------------------""")
str11 = "Return the number of non-overlapping occurrences of substring sub in string S[start:end]."
print("str11={}".format(str11))
result = str11.count("str")
print("str11.count('str')执行结果为：", result)
print("str11.count('tab')执行结果为：", str11.count('tab')) # 找不到为0
print("str11.count('t', 5)执行结果为：", str11.count('t', 5)) # 从第5个字符开始统计
print("str11.count('t', 5, 10)执行结果为：", str11.count('t', 5, 10))

print("""
----------------------------------------
（12）str.find(sub[, start[, end]]) -> int
  Return the lowest index in S where substring sub is found,
  such that sub is contained within S[start:end].  Optional
  arguments start and end are interpreted as in slice notation.
  Return -1 on failure.
  检测 sub 是否包含在字符串中
  如果指定范围 start 和 end ，则检查是否包含在指定范围内，
    如果包含返回开始的索引值，否则返回-1
----------------------------------------""")
str12 = "Return the lowest index in S where substring sub is found."
print("str12={}".format(str12))
result = str12.find("in")
print("str12.find('in')执行结果为：", result)
print("str12.find('in', 20, 24)执行结果为：", str12.find('in', 20, 24))
print("str12.find('in', 20)执行结果为：", str12.find('in', 20))

print("""
----------------------------------------
（13）str.rfind(sub[, start[, end]]) -> int
  Return the highest index in S where substring sub is found,
  such that sub is contained within S[start:end].  Optional
  arguments start and end are interpreted as in slice notation.
  Return -1 on failure.
  类似于 find()函数，不过是从右边开始查找
----------------------------------------""")

print("""
----------------------------------------
（14）str.index(sub[, start[, end]]) -> int
  Return the lowest index in S where substring sub is found,
  such that sub is contained within S[start:end].  Optional
  arguments start and end are interpreted as in slice notation.
  Raises ValueError when the substring is not found.
  跟find()方法一样，只不过如果sub不在字符串中会报一个异常。
----------------------------------------""")
str14 = "Return the lowest index in S where substring sub is found."
print("str14={}".format(str14))
result = str14.index("in")
print("str14.index('in')执行结果为：", result)
#print("str14.index('in', 20, 24)执行结果为：", str14.index('in', 20, 24)) # 找不到会抛出异常
print("str14.index('in', 20)执行结果为：", str14.index('in', 20))

print("""
----------------------------------------
（15）str.rindex(sub[, start[, end]]) -> int
  Return the highest index in S where substring sub is found,
  such that sub is contained within S[start:end].  Optional
  arguments start and end are interpreted as in slice notation.
  Raises ValueError when the substring is not found.
  类似于 index()，不过是从右边开始.
----------------------------------------""")

print("""
四、格式化字符串（16）——（17），共计2个
----------------------------------------
（16）str.format(*args, **kwargs) -> str
  Return a formatted version of S, using substitutions from args and kwargs.
  The substitutions are identified by braces ('{' and '}').
  返回格式化的字符串，用args和kwargs指定的字串去填充{}
  args：按照位置顺序填充
  kwargs：按照关键字指定的字符串去填充
  可以理解为{}代表形参，*args代表不定长的位置实参，**kwargs代表不定长的关键字实参
----------------------------------------""")
cores = {"Chinese": 90, "Math": 95 ,"English": 92}
course = ["语文", "数学" ,"英语"]
str16 = "{}成绩：{}分，{}成绩：{}分，{}成绩：{}分".format(
  "语文", 90, "数学", 95, "英语", 92
)
print(str16)
print("{2}成绩：{3}分，{0}成绩：{1}分，{4}成绩：{5}分".format(
  "语文", 90, "数学", 95, "英语", 92
))
print("{0}成绩：{Chinese}分，{1}成绩：{Math}分，{2}成绩：{English}分".format(
  *course, **cores
))

print("""
----------------------------------------
（17）str.format_map(mapping) -> str
  Return a formatted version of S, using substitutions from mapping.
  The substitutions are identified by braces ('{' and '}').
  传入字典作为关键字参数，key的值value填充{}
  mapping必须是字典
----------------------------------------""")
cores = {"Chinese": 90, "Math": 95 ,"English": 92}
str17 = "语文成绩：{Chinese}分，数学成绩：{Math}分，英语成绩：{English}分".format_map(cores)
print(str17)

print("""
五、判断字符串（18）——（31），共计14个
----------------------------------------
（18）str.isalnum()
  Return True if the string is an alpha-numeric string, False otherwise.
  A string is alpha-numeric if all characters in the string are alpha-numeric and
  there is at least one character in the string.
  检测字符串是否由字母和数字组成
  如果字符串至少有一个字符并且所有字符都是字母或数字则返回 True，否则返回 False
----------------------------------------""")

print("""
----------------------------------------
（19）str.isalpha()
  Return True if the string is an alphabetic string, False otherwise.
  A string is alphabetic if all characters in the string are alphabetic and there
  is at least one character in the string.
  检测字符串是否只由字母或文字组成
  如果字符串至少有一个字符并且所有字符都是字母或中文字则返回 True, 否则返回 False
----------------------------------------""")

print("""
----------------------------------------
（20）str.isascii()
  Return True if all characters in the string are ASCII, False otherwise.
  ASCII characters have code points in the range U+0000-U+007F.
  Empty string is ASCII too.
  如果字符串为空或字符串中的所有字符都是 ASCII,则返回 True,否则返回 False
  ASCII 字符的码位在 U+0000-U+007F 范围内
----------------------------------------""")

print("""
----------------------------------------
（21）str.isdecimal()
  Return True if the string is a decimal string, False otherwise.
  A string is a decimal string if all characters in the string are decimal and
  there is at least one character in the string.
  检查字符串是否只包含十进制字符，如果是返回 true，否则返回 false
----------------------------------------""")

print("""
----------------------------------------
（22）str.isdigit()
  Return True if the string is a digit string, False otherwise.
  A string is a digit string if all characters in the string are digits and there
  is at least one character in the string.
  检测字符串是否只由数字组成
  如果字符串只包含数字则返回 True 否则返回 False.
----------------------------------------""")

print("""
----------------------------------------
（23）str.isnumeric()
  Return True if the string is a numeric string, False otherwise.
  A string is numeric if all characters in the string are numeric and there is at
  least one character in the string.
  检测字符串是否只由数字组成，数字可以是：
    Unicode 数字，全角数字（双字节），罗马数字，汉字数字，指数类似 ² 与分数类似 ½ 也属于数字
  如果字符串中只包含数字字符，则返回 True，否则返回 False
----------------------------------------""")

print("""
----------------------------------------
（24）str.isidentifier()
  Return True if the string is a valid Python identifier, False otherwise.
  Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
  such as "def" or "class".
  用于判断字符串是否是有效的 Python 标识符，可用来判断变量名是否合法
----------------------------------------""")

print("""
----------------------------------------
（25）str.islower()
  Return True if the string is a lowercase string, False otherwise.
  A string is lowercase if all cased characters in the string are lowercase and
  there is at least one cased character in the string.
  检测字符串是否由小写字母组成，如果字符串中包含至少一个区分大小写的字符，
  并且所有这些(区分大小写的)字符都是小写，则返回 True，否则返回 False。
----------------------------------------""")

print("""
----------------------------------------
（26）str.isprintable()
  Return True if the string is printable, False otherwise.
  A string is printable if all of its characters are considered printable in
  repr() or if it is empty.
  用于判断字符串中所有字符是否都是可打印字符(in repr())或字符串为空。
  Unicode字符集中“Other” “Separator”类别的字符为不可打印的字符（但不包括ASCII码中的空格（0x20））。可用于判断转义字符。
  ASCII码中第0～32号及第127号是控制字符；第33～126号是可打印字符，其中第48～57号为0～9十个阿拉伯数字；65～90号为26个大写英文字母，97～122号为26个小写英文字母。
----------------------------------------""")

print("""
----------------------------------------
（27）str.isspace()
  Return True if the string is a whitespace string, False otherwise.
  A string is whitespace if all characters in the string are whitespace and there
  is at least one character in the string.
  检测字符串是否只由空白字符组成
  如果字符串中只包含空白字符，则返回 True，否则返回 False.
----------------------------------------""")

print("""
----------------------------------------
（28）str.istitle()
  Return True if the string is a title-cased string, False otherwise.
  In a title-cased string, upper- and title-case characters may only
  follow uncased characters and lowercase characters only cased ones.
  是否是"标题化"的字符串的判断,就是说所有单词的首个字母转化为大写，其余字母均为小写
  是标题化字符串返回True，否则False
----------------------------------------""")

print("""
----------------------------------------
（29）str.isupper()
  Return True if the string is an uppercase string, False otherwise.
  A string is uppercase if all cased characters in the string are uppercase and
  there is at least one cased character in the string.
  检测字符串中所有的字母是否都为大写
  如果字符串中包含至少一个区分大小写的字符，并且所有这些(区分大小写的)字符都是大写，则返回 True，否则返回 False
----------------------------------------""")

print("""
----------------------------------------
（30）str.startswith(prefix[, start[, end]]) -> bool
  Return True if S starts with the specified prefix, False otherwise.
  With optional start, test S beginning at that position.
  With optional end, stop comparing S at that position.
  prefix can also be a tuple of strings to try.
  用法：用于判断字符串是否是某几个字符串开头，返回值为布尔类型bool（true|false）。
----------------------------------------""")
str30 = "Return True if S starts with the specified prefix, False otherwise."
prefix = "Return"
print(str30.startswith(prefix))
print(str30.startswith(prefix, 20))
print(str30.startswith("starts", 17))

print("""
----------------------------------------
（31）str.endswith(suffix[, start[, end]]) -> bool
  Return True if S ends with the specified suffix, False otherwise.
  With optional start, test S beginning at that position.
  With optional end, stop comparing S at that position.
  suffix can also be a tuple of strings to try.
  用法：用于判断字符串是否是某几个字符串结尾，返回值为布尔类型bool（true|false）。
  str：字符串，待判断字符串
  suffix：后缀，判断字符串后缀是否是这个后缀，可为单字符也可为多字符。
  start：索引字符串开始序号，可选，默认为0，从第一个位置开始。
  end：索引字符串结束序号，可选，默认为字符串长度len(str)，从最后位置结束。
      若填写则开始字符串也要填，start填，end可选填。
  注意：标点符号要区分中英文
----------------------------------------""")

print("""
六、删除子串（32）——（36），共计5个
----------------------------------------
（32）str.lstrip(chars=None)
  Return a copy of the string with leading whitespace removed.
  If chars is given and not None, remove characters in chars instead.
  截掉字符串左边的空格或指定字符chars
  注意：chars是一个或多个字符，实现方法为：
    从chars中取第一个字符与str左边首字符匹配，如果能够匹配上，
    那么，继续与str第二个字符匹配，如果不能匹配，则
    从chars中取第二个字符与str左边第二个字符匹配，如果不能匹配，那么去掉第一个即可，
    如果能够匹配，再检查第三个字符
----------------------------------------""")
print("今天天气不错".lstrip("今天")) # 输出：气不错

print("""
----------------------------------------
（33）str.rstrip(chars=None)
  Return a copy of the string with trailing whitespace removed.
  If chars is given and not None, remove characters in chars instead.
  删除字符串末尾的空格或指定字符
----------------------------------------""")

print("""
----------------------------------------
（34）str.strip(chars=None)
  Return a copy of the string with leading and trailing whitespace removed.
  If chars is given and not None, remove characters in chars instead.
  在字符串上执行 lstrip()和 rstrip()
----------------------------------------""")

print("""
----------------------------------------
（35）str.removeprefix(prefix)
  Return a str with the given prefix string removed if present.
  If the string starts with the prefix string, return string[len(prefix):].
  Otherwise, return a copy of the original string.
  返回删除前缀prefix的字符串
  如果没有prefix前缀，返回copy原字符串的字符串
  注意：匹配是以prefix作为整体进行匹配的
----------------------------------------""")
print("今天天气不错".removeprefix("今天")) # 输出：天气不错

print("""
----------------------------------------
（36）str.removesuffix(self, suffix, /)
  Return a str with the given suffix string removed if present.
  If the string ends with the suffix string and that suffix is not empty,
  return string[:-len(suffix)]. Otherwise, return a copy of the original
  string.
  返回删除后缀suffix的字符串
  如果没有suffix前缀，返回copy原字符串的字符串
----------------------------------------""")

print("""
七、字符串连接（37），共计1个
----------------------------------------
（37）sep.join(iterable)
  Concatenate any number of strings.
  The string whose method is called is inserted in between each given string.
  The result is returned as a new string.
  Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
  使用字符串sep将iterable中的元素连接起来，生成一个新的字符串，并返回连接好的新字符串
  sep：用于作为连接符的字符串
  iterable：需要连接的可迭代对象
----------------------------------------""")
str37 = "The string whose method is called is inserted in between each given string."
strList = str37.split(" ")
print("strList = str37.split(' ')", strList)
print("str.join(iterable)结果：", ' '.join(strList))

print("""
八、字符串分割（38）——（42），共计5个
----------------------------------------
（38）str.partition(sep)
  Partition the string into three parts using the given separator.
  This will search for the separator in the string.  If the separator is found,
  returns a 3-tuple containing the part before the separator, the separator
  itself, and the part after it.
  If the separator is not found, returns a 3-tuple containing the original string
  and two empty strings.
  从左边开始搜索指定分隔符sep，找到第一个sep后，返回以sep前，sep和sep后三部分字符串作为元素的三元组
  如果sep未找到，返回原字符串和两个空字符串组成的三元组
----------------------------------------""")
str38 = "Partition the string into three parts using the given separator."
sep = " the "
strTuple = str38.partition(sep)
print("str38.partition(sep)的结果是：", strTuple)

print("""
----------------------------------------
（39）str.rpartition(sep)
  Partition the string into three parts using the given separator.
  This will search for the separator in the string, starting at the end. If
  the separator is found, returns a 3-tuple containing the part before the
  separator, the separator itself, and the part after it.
  If the separator is not found, returns a 3-tuple containing two empty strings
  and the original string.
  从右边开始搜索
----------------------------------------""")

print(r"""
----------------------------------------
（40）str.split(sep=None, maxsplit=-1)
  Return a list of the words in the string, using sep as the delimiter string.
  sep
    The delimiter according which to split the string.
    None (the default value) means split according to any whitespace,
    and discard empty strings from the result.
  maxsplit
    Maximum number of splits to do.
    -1 (the default value) means no limit.
  指定分隔符sep对字符串进行切片，如果指定第二个参数maxsplit，则只分隔maxsplit次，最后返回一个列表
  sep：用于分割的字符串，默认sep=None，即默认为所有的空字符，包括空格、换行(\n)、制表符(\t)等
  maxsplit：分割次数。默认为 -1, 即分隔所有
  注意：字符串开头存在分隔符，会分割出一个空字符串
----------------------------------------""")
str40 = "Return a list of the words in the string, using sep as the delimiter string."
print("str40.split(' ')分割返回列表：", str40.split(' '))

print("""
----------------------------------------
（41）str.rsplit(sep=None, maxsplit=-1)
  Return a list of the words in the string, using sep as the delimiter string.
    sep
      The delimiter according which to split the string.
      None (the default value) means split according to any whitespace,
      and discard empty strings from the result.
    maxsplit
      Maximum number of splits to do.
      -1 (the default value) means no limit.
  Splits are done starting at the end of the string and working to the front.
  split是从左向右找，rsplit是从右向左找，其余功能相同
----------------------------------------""")

print(r"""
----------------------------------------
（42）str.splitlines(keepends=False)
  Return a list of the lines in the string, breaking at line boundaries.
  Line breaks are not included in the resulting list unless keepends is given and
  true.
  按照换行符('\r', '\r\n', \n')分隔，返回一个包含各行作为元素的列表
  如果参数 keepends 为 False，不包含换行符，如果为 True，则保留换行符
----------------------------------------""")
str42 = "Return a list of the lines in the string, \nbreaking at line boundaries."
print(str42)
print("str42.splitlines()按换行符分割，输出列表，不包括换行符：", str42.splitlines())
print("str42.splitlines(True)按换行符分割，输出列表，包括换行符：", str42.splitlines(True))

print("""
九、部分替换（43）——（45），共计3个
----------------------------------------
（43）str.replace(old, new, count=-1)
  Return a copy with all occurrences of substring old replaced by new.
    count
      Maximum number of occurrences to replace.
      -1 (the default value) means replace all occurrences.
  If the optional argument count is given, only the first count occurrences are
  replaced.
  将字符串中的 old 替换成 new,
  如果 count 指定，则替换不超过 count 次
  默认count=-1代表所有符合的都替换
----------------------------------------""")
str43 = "Return a copy with all occurrences of substring old replaced by new."
print(str43.replace("all", "ALL"))
print(str43.replace("r", "R")) # 默认全部替换
print(str43.replace("r", "R", 2)) # 替换两次

print("""
----------------------------------------
（44）str.maketrans(intab, outtab[,delchars])
  Return a translation table usable for str.translate().
  If there is only one argument, it must be a dictionary mapping Unicode
  ordinals (integers) or characters to Unicode ordinals, strings or None.
  Character keys will be then converted to ordinals.
  If there are two arguments, they must be strings of equal length, and
  in the resulting dictionary, each character in x will be mapped to the
  character at the same position in y. If there is a third argument, it
  must be a string, whose characters will be mapped to None in the result.
  参数：
    intab -- 字符串中要替代的字符组成的字符串，即需要转换的字符。
    outtab -- 相应的映射字符的字符串，即转换为什么字符。
    delchars -- 可选参数，表示要删除的字符组成的字符串
  intab和outtab两个字符串的长度必须相同，为一一对应的关系
  返回映射表talbe，用于str.translate(table)
----------------------------------------""")
intab = "ahngt"
outtab = "AHNGT"
delchars = "."
table = str.maketrans(intab,outtab,delchars)
print(table)

print("""
----------------------------------------
（45）str.translate(table)
  Replace each character in the string using the given translation table.
    table
      Translation table, which must be a mapping of Unicode ordinals to
      Unicode ordinals, strings, or None.
  The table must implement lookup/indexing via __getitem__, for instance a
  dictionary or list.  If this operation raises LookupError, the character is
  left untouched.  Characters mapped to None are deleted.
  根据 table 给出的表(包含 256 个字符)转换 string 的字符，table表包含三个字段：
    intab: 需要转换的字符组成的字符串
    outtab: 对应转换成的字符组成的字符串
    deltab: 需要删除的字符组成的字符串
    table = maketrans(intab, outtab, deltab)
----------------------------------------""")
str45 = "Replace each character in the string using the given translation table."
print(str45.translate(table))

print("""
十、其它（46）——（47），共计2个
----------------------------------------
（46）str.expandtabs(tabsize=8)
  Return a copy where all tab characters are expanded using spaces.
  If tabsize is not given, a tab size of 8 characters is assumed.
  把字符串 string 中的 tab 符号转为空格，tab 符号默认的空格数是 8
----------------------------------------""")
str46 = "Return\ta copy where all tab characters are expanded using spaces."
print(str46.expandtabs())
print(str46.expandtabs(16))

print("""
----------------------------------------
（47）str.encode(encoding='utf-8', errors='strict')
  Encode the string using the codec registered for encoding.
  encoding
    The encoding in which to encode the string.
  errors
    The error handling scheme to use for encoding errors.
    The default is 'strict' meaning that encoding errors raise a
    UnicodeEncodeError.  Other possible values are 'ignore', 'replace' and
    'xmlcharrefreplace' as well as any other name registered with
    codecs.register_error that can handle UnicodeEncodeErrors.
  以 encoding 指定的编码格式编码 string，
  如果出错默认报一个ValueError 的异常，除非 errors 指定的是'ignore'或者'replace'
  注意：
    bytes.decode(encoding="utf-8", errors="strict")
      Python3 中没有 decode 方法，但我们可以使用 bytes 对象的 decode() 方法来解码给定的 bytes 对象，
      这个 bytes 对象可以由 str.encode() 来编码返回。
----------------------------------------""")
# 暂时不用学习